// 消费者
var EventEmitter = require('events')
var redis = require('redis')
var bluebird = require('bluebird')

var client = redis.createClient('6379', '127.0.0.1')
var rp = require('../utils/request')
// var rp = url => {
//   return Promise.resolve(url)
// }

bluebird.promisifyAll(redis.RedisClient.prototype)
bluebird.promisifyAll(redis.Multi)
class Consumer extends EventEmitter {
  constructor() {
    super()
    this.status = 'ready'
  }
}
var consumer = new Consumer()
consumer.on('pause', () => {
  console.log('Consumer will pause')
  this.status = 'pause'
})
consumer.on('resume', () => {
  if (this.status === 'pause') {
    this.status = 'begin'
    this.emit('begin')
  }
})
consumer.on('begin', async () => {
  this.status = 'begin'
  while(true) {
    var value = await client.lpopAsync('test')
    // 调用封装好的 request 方法
    await rp(value).then(res => console.log(value, res))
    if (this.status === 'pause') {
      break
    }
  }
})
async function getListLength() {
  // 获取缓冲区大小
  var length = await client.llenAsync('test')
  if (length == 0 && this.status == 'begin') {
    consumer.emit('pause')
  } else if (this.status === 'pause' && length > 1000) {
    // 当缓冲区大于 1000 时才启动消费者。避免在临界值附近反复切换状态
    consumer.emit('resume')
  }
  console.log('current length ' + length)
}
consumer.emit('begin')
setInterval(getListLength, 30000)